package ssm.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: lzp
 * @Date: 2020/10/9 17:28
 * @Description: 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    List<String> urls = new ArrayList<String>();

    /**
     * 构造方法初始化放行路由
     */
    public LoginInterceptor() {
        urls.add("login");
        urls.add("register");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //直接放行登录注册等路由
        String uri = request.getRequestURI();
        for (String url : urls) {
            if (uri.contains(url)) {
                return true;
            }
        }
        HttpSession session = request.getSession(false);
        if (session != null) {
            if (session.getAttribute("admin") != null) {
                return true;
            }
        }
        response.sendRedirect(request.getContextPath()+"/pages/comment/login_err.jsp");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
